package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Car;
import cn.wolfcode.crm.query.CarObjectQuery;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.service.ICarService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PermissionName;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("car")
public class CarController {
    @Autowired
    private ICarService carMapper;

    @RequiresPermissions("car:index")
    @PermissionName("车辆信息主页")
    @RequestMapping("index")
    public String index( @ModelAttribute("qo") CarObjectQuery qo) {
        return "car/list";
    }

    @RequiresPermissions("car:list")
    @PermissionName("车辆信息查询")
    @RequestMapping("list")
    @ResponseBody
    public PageResult<Car> list( @ModelAttribute("qo") CarObjectQuery qo) {
        PageResult<Car> list = carMapper.query(qo);
        return list;
    }
    @RequestMapping("query")
    @ResponseBody
    public List<Car> query( ) {
        return carMapper.getAll();
    }


    @RequiresPermissions("car:delete")
    @PermissionName("车辆信息删除")
    @RequestMapping("delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        JsonResult jsonResult = new JsonResult();
        try {
            if (id != null) {
                carMapper.delete(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.markErrorMsg("删除车辆信息失败");
        }
        return jsonResult;
    }


    @RequiresPermissions("car:saveOrUpdate")
    @PermissionName("车辆信息创建更新")
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Car car) {
        JsonResult jsonResult = new JsonResult();
        try {
            if (car.getId() != null) {
                carMapper.update(car);
            } else {
                carMapper.save(car);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.markErrorMsg("保存或更新车辆信息失败");
        }
        return jsonResult;
    }


}
